package cn.duwey.scs.common.base;

import java.util.ArrayList;
import java.util.List;

public abstract class BaseServiceImpl<T extends BaseEntity> implements IBaseService<T> {

    protected abstract BaseRepository<T, Long>  getRepository();

    protected abstract boolean passCheckBeforeInsert(T entity);

    @Override
    public T findByPrimaryKey(Long id) {

        return this.getRepository().findById(id).orElse(null);
    }

    @Override
    public T save(T entity) {
        if (passCheckBeforeInsert(entity)) {
            return this.getRepository().save(entity);
        }
        return null;
    }

    @Override
    public Iterable<T> saveAll(Iterable<T> entities) {
        List<T> list = new ArrayList<>();

        for (T entity: entities) {
            if (passCheckBeforeInsert(entity)) {
                list.add(entity);
            }
        }

        return this.getRepository().saveAll(list);

    }

    @Override
    public void update(T entity) {
        this.getRepository().update(entity);
    }

    @Override
    public void deleteByPrimaryKey(Long id) {
        this.getRepository().deleteById(id);
    }

    @Override
    public void delete(T entity) {
        this.getRepository().delete(entity);
    }

    @Override
    public void deleteAll(Iterable<T> entities) {
        this.getRepository().deleteAll(entities);
    }

    @Override
    public void deleteAll() {
        this.getRepository().deleteAll();
    }

    @Override
    public void deleteAllInBatch() {
        this.getRepository().deleteAllInBatch();
    }
}
